package me.gavin.ext

import android.os.Build
import android.text.Editable
import android.text.Html
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.getSystemService
import androidx.core.text.HtmlCompat

fun View.onClick(block: () -> Unit) = setOnClickListener { block.invoke() }

inline fun <reified T : ViewGroup.LayoutParams> View.layoutParams() = layoutParams as T

inline fun <reified T : CoordinatorLayout.Behavior<*>> CoordinatorLayout.LayoutParams.behavior() = behavior as T

val TextView.textTrim get() = text.toString().trim()

val TextView.lengthTrim get() = textTrim.length

val TextView.toIntOr0 get() = textTrim.toIntOrNull() ?: 0
val TextView.toLongOr0 get() = textTrim.toLongOrNull() ?: 0L
val TextView.toFloatOr0 get() = textTrim.toFloatOrNull() ?: 0f
val TextView.toDoubleOr0 get() = textTrim.toDoubleOrNull() ?: 0.0

fun TextView.setTextHtml(html: String) {
    text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

fun TextView.setDrawableLeft(drawableRes: Int) {
    setCompoundDrawablesWithIntrinsicBounds(drawableRes, 0, 0, 0)
}

fun TextView.setDrawableRight(drawableRes: Int) {
    setCompoundDrawablesWithIntrinsicBounds(0, 0, drawableRes, 0)
}

fun TextView.afterTextChanged(block: (Editable) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(s: Editable) {
            block.invoke(s)
        }
    })
}

//fun TextView.toObservable() = Observable.create<CharSequence> { emitter ->
//    emitter.onNext(this.text)
//    this.addTextChangedListener(object : TextWatcher {
//        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
//        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
//        override fun afterTextChanged(s: Editable) {
//            emitter.onNext(s)
//        }
//    })
//}

fun EditText.setSelectionEnd() {
    setSelection(length())
}

fun EditText.showSoftInput() {
    requestFocus()
    context.getSystemService<InputMethodManager>()?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun View.hideSoftInput() {
    context.getSystemService<InputMethodManager>()
        ?.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}